package com.starsoft.frame.base.service;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.starsoft.frame.base.bean.BaseAcount;
import com.starsoft.frame.base.bean.BaseRole;
import com.starsoft.frame.base.bean.BaseUser;
import com.starsoft.frame.base.bean.UserContext;
import com.starsoft.frame.base.dao.AcountDao;
import com.starsoft.frame.base.dao.UserDao;
import com.starsoft.frame.core.orm.PageObject;
import com.starsoft.frame.core.service.BaseService;
import com.starsoft.frame.util.MapUtil;
import com.starsoft.frame.util.StringUtil;

@Service
public class UserService extends BaseService{
	
	private static ThreadLocal<UserContext> threaduser=new ThreadLocal<UserContext>();
	
	public static void setUserContext(UserContext user){
		threaduser.set(user);
	}
	
	public static UserContext getUserContext(){
		return threaduser.get();
	}

	@Autowired
	AcountDao acountDao;
	
	@Autowired 
	UserDao userDao;
	@Autowired
	PreferenceService ps;
	
	public BaseUser getUser(String userName){
		return userDao.getUser(userName);
	}
	
	public BaseAcount getAcount(Integer acountId){
		return acountDao.get(acountId);
	}
	
	public void saveUser(BaseUser user){
		if(user.getUserPwd()==null){
			user.setUserPwd(StringUtil.getMD5(user.getUserName()));
		}
		userDao.saveOrUpdate(user);
		if(user.getDefautAcount()==null){
			BaseAcount count = acountDao.insertDefaultAcount(user);
			user.setDefautAcount(count.getAcountId());
		}
	}
	
	public void deleteUser(BaseUser user){
		userDao.delete(user);
	}
	
	public Map<String, Object> pageQueryUser(PageObject po){
		return acountDao.pageQuery(BaseUser.class, po);
	}

	public BaseUser checkUser(String userName, String pwd){
		return userDao.getUser(userName, pwd);
	}

	public UserContext getUserContext(String name){
		BaseUser user = userDao.getUser(name);
		if(user==null){
			throw new RuntimeException("user not exists");
		}
		BaseAcount defaultAcount = acountDao.get(user.getDefautAcount());
		UserContext context = new UserContext(user, defaultAcount);
		UserService.setUserContext(context);
		return context;
	}
	
	public void updateUserContext(){
		UserContext context = UserService.getUserContext();
		context.setUser(userDao.get(context.getUserId()));
	}
	
	public Map<String,Object> convertUser(BaseUser user){
		Map<String,Object> userMap = MapUtil.toMap(user);
		BaseRole role = hibernateDao.get(BaseRole.class, user.getRoleId());
		userMap.put("roleName", role.getRoleName());
		userMap.put("homePage", ps.getPreference("homePage",  UserService.getUserContext()));
		return userMap;
	}
}
